package com.jb.web.bean.list;

import com.jb.web.bean.HtmlItem;
import com.jb.web.bean.Link;
import com.jb.web.bean.ListBean;
import com.jb.web.bean.Page;
import com.jb.web.context.WebContext;
import com.jb.web.renderer.ImageRenderer;

import com.jb.faces.component.UIComponent;


public class NavButtonRenderer extends ImageRenderer {
    public StringBuffer render(WebContext pCtx, UIComponent itemToRender) {
        resolve(itemToRender);
        return super.render(pCtx, itemToRender);
    }

    private UIComponent getList(UIComponent hItem) {
        if (hItem == null) {
            return hItem;
        }
        if (hItem instanceof ListBean) {
            return hItem;
        }
        if (hItem instanceof Page) {
            return null;
        }
        return getList(hItem.getParent());
    }

    private void resolve(UIComponent item) {
        Link hLink = (Link)item;
        Page page = hLink.getPage();
        HtmlItem hItem = (HtmlItem)page.getContained();
        ListBean lb = (ListBean)getList(hItem);
        String value = hLink.getDefaultValue();

        if (lb != null) {
            if ("next".equalsIgnoreCase(value)) {
                hLink.setOnCommand("${" + lb.getClientId() + ".nextPage}");
            }

            if ("last".equalsIgnoreCase(value)) {
                hLink.setOnCommand("${" + lb.getClientId() + ".lastPage}");
            }

            if ("previous".equalsIgnoreCase(value)) {
                hLink.setOnCommand("${" + lb.getClientId() + ".previousPage}");
            }

            if ("first".equalsIgnoreCase(value)) {
                hLink.setOnCommand("${" + lb.getClientId() + ".firstPage}");
            }
        }
    }
}
